package com.zrb.mobile;

import org.apache.http.Header;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
 
import com.zrb.mobile.adapter.model.UserDtos;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.CenterProgressWebView;
import com.zrb.mobile.ui.CenterProgressWebView.IOnJsPrompt;
import com.zrb.mobile.ui.CenterProgressWebView.ScrollInterface;
import com.zrb.mobile.utility.AnimationManager;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CollectionHelper;
import com.zrb.mobile.utility.CollectionHelper.onCollectionListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ZrbRestClient;

public class Project_info_lience extends BaseActivity implements OnClickListener, IOnJsPrompt, ScrollInterface, onCollectionListener {

	long uid;
	String uname;
	EditText email;
	CenterProgressWebView mWebView;
    int projectId,pId;//aotuId
    String mtitle,pName,tino;
    TextView btnComment;
    boolean isFavorite=false;
	TextView btnfavorite,textView1,textView2,btn_cancel;
	CollectionHelper mCollectionHelper;
	LinearLayout mBottomBar;
	Dialog AuthDialog,CheckPwdDialog;
	Handler mhandler=new Handler();
	public static boolean hasNew=false;
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
 	  
		setContentView(R.layout.project_infos_lience);
		if (bundle != null)
			restoreSelf(bundle);
		else {
 			projectId = this.getIntent().getIntExtra("projectId", -1);
			mtitle = this.getIntent().getStringExtra("title");
		}
 		initView();
 	}
	@Override
	protected void onResume() {
 	   if(hasNew) {
		   hasNew=false;
		   if(null!=mWebView)  mWebView.loadUrl("javascript:refreshComment()");
 	   }
	   super.onResume();
	}
	
	@Override
	protected  void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putInt("projectId", projectId);
        outState.putString("title", mtitle);
    }

    private void restoreSelf(Bundle savedInstanceState)
    {
    	projectId = savedInstanceState.getInt("projectId",-1);
    	mtitle = savedInstanceState.getString("title");
    }

	private void initView() {
  		
		mCollectionHelper = new CollectionHelper(this.getApplicationContext(),1);
		mCollectionHelper.setOnCollectionListener(this);
		
		mBottomBar=(LinearLayout)this.findViewById(R.id.bottombar);
		mBottomBar.setVisibility(View.GONE);
		
		TextView tmpSurvey=(TextView)this.findViewById(R.id.btn_project_survey);
		tmpSurvey.setOnClickListener(this);
		
		if(AppSetting.curUser!=null){
 		/*	if(AppSetting.curUser.userType.equals("2")) //gov
				tmpSurvey.setVisibility(View.GONE);*/
		}
		
		this.findViewById(R.id.btn_project_call).setOnClickListener(this);
		this.findViewById(R.id.btn_project_im).setOnClickListener(this);
	 	
		
// 		this.findViewById(R.id.rightbutton_comment_list).setOnClickListener(this);
//		this.findViewById(R.id.write_comments_layout).setOnClickListener(this);
 		
		View lefticon= this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
		this.findViewById(R.id.btn_share).setOnClickListener(this);
		btnfavorite=(TextView)this.findViewById(R.id.btn_favorite);
		btnfavorite.setOnClickListener(this);
      	
	 	showfavoriteState();
      	btnComment=(TextView)this.findViewById(R.id.btn_font);
      	btnComment.setText("����");
      	btnComment.setOnClickListener(this);
      	Drawable top=this.getResources().getDrawable(R.drawable.project_bar_comment);
      	btnComment.setCompoundDrawablesWithIntrinsicBounds(null,top,null,null);
      	
 	    mWebView = (CenterProgressWebView) this.findViewById(R.id.webView1);
 	    mWebView.setOnJsPromptListener(this);
 	    mWebView.setOnCustomScroolChangeListener(this);
 	    
 		String url =   AppSetting.BASE_URL + "pro/proDetails?id=" + projectId;
 		
 		CommonUtil.InfoLog("tagurl", url);
		 mWebView.loadUrl(url);
 		//mWebView.loadUrl("http://www.baidu.com");

	}

	private void showfavoriteState(){
    	/*if(AppSetting.curUser==null) return;
    	isFavorite=	mCollectionHelper.isExistId(projectId,false);
     	if(isFavorite){ 
     		btnfavorite.setSelected(true);
     		btnfavorite.setText("�ѹ�ע");
     	}; */
     }
	
	private void shareLink(){
		 // String imageLink=AppSetting.BASE_URL+"newsapp/newsDetails?id="+newid;
		  Intent intent = new Intent(Project_info_lience.this,News_ShareActivity.class);
		  intent.putExtra("title", mtitle);
		 // intent.putExtra("url",imageLink);
		  intent.putExtra("url", mWebView.getUrl());
		  startActivity(intent);
	}
 	
	private void showtoolbar(boolean visible){
 		if (visible) {
 			mhandler.postDelayed(new Runnable(){
 				@Override
				public void run() {
					// TODO Auto-generated method stub
					  mBottomBar.startAnimation(AnimationManager.getInstance().getBottomBarShowAnimation());
			 		  mBottomBar.setVisibility(View.VISIBLE);
				}
	  		}, 200);
 		}
		else{
			mhandler.postDelayed(new Runnable(){
 				@Override
				public void run() {
		          mBottomBar.startAnimation(AnimationManager.getInstance().getBottomBarHideAnimation());  
		          mBottomBar.setVisibility(View.GONE);
 				}
	  		}, 500);
 		}
	}
	
	/*this.findViewById(R.id.img_comments).setOnClickListener(this);
	this.findViewById(R.id.write_comments_layout).setOnClickListener(this);*/
	
	private void goWritecomment(Class<?>  curclass,int reqcode){
 		 if( null != AppSetting.curUser){
			 Intent it4 = new Intent(Project_info_lience.this, curclass);
			 it4.putExtra("projectId", projectId);
			 this.startActivity(it4);
		 }else{
			 Intent it = new Intent(this, User_phone_login.class);
	 		 it.putExtra("forResult", true);
			 this.startActivityForResult(it,reqcode );
 		 }
 	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.btn_project_call:
 		     Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +Constants.serverPhone));
			 this.startActivity(intent);
			 break;
		case R.id.btn_project_im:
			 startChat();
			 break; 
			 
//		 case R.id.write_comments_layout:
//			 goWritecomment(Project_commentActivity.class,102);
// 			 break;
//		 case R.id.rightbutton_comment_list:
//			 Intent it4 = new Intent(Project_info_lience.this, Project_commentlist_Activity.class);
//			 it4.putExtra("projectId", projectId);
//		     startActivity(it4); 
// 			 break;
	 	 case R.id.title_left_root:
			this.finish();
			break;
		  case R.id.btn_share:
 			  shareLink();
			  break;
		  case R.id.btn_favorite:
			  onClickCollect(projectId);
			  break;
 		  case  R.id.btn_font:
  		      goWritecomment(Project_commentActivity.class,102);
			  break;
 		  case R.id.btn_project_survey:
 			  checkSurvey();
 			  break;
		}
 	}
	
   private void startChat(){
	   
	/* 
                if(hxid.equals(LocalUserInfo.getInstance(getApplicationContext()).getUserInfo("hxid"))){
                    Toast.makeText(getApplicationContext(), "���ܺ��Լ����졣��", Toast.LENGTH_SHORT).show();
                    return ;
                }*/
	   
		 if(null != AppSetting.curUser){
			   Intent intent = new Intent();
             //  intent.putExtra("userId", "13556162989");
			  /* intent.putExtra("userId", "888279");*/
			/*   intent.putExtra("userId",UserUtils.kefuName);// "zrb_2000000333"
			   
               intent.putExtra("userNick", "���ڱ��ͷ�");
               intent.putExtra("userAvatar", "avatar");
               intent.setClass(Project_info_lience.this, com.zrb.chat.activity.ChatActivity.class);*/
               startActivity(intent);
		 }else{
			 Intent it = new Intent(this, User_phone_login.class);
	 		 it.putExtra("forResult", true);
			 this.startActivityForResult(it,105 );
 		 }
   }
	
   private void checkSurvey(){
	   
	   if(AppSetting.curUser!=null){
		/*	if(AppSetting.curUser.userType.equals("2")) //gov
			{	
 				CommonUtil.showToast("��ǰ����ǹ���Ա�����ܽ��п���", Project_info_lience.this);
			   return;
			}*/
		}
	   if(AppSetting.curUser==null){
			 Intent it = new Intent(this, User_phone_login.class);
			 it.putExtra("forResult", true);
			 this.startActivityForResult(it, 101);
		    return;
		}
		else{
	      Intent it2 = new Intent(Project_info_lience.this, Project_surveyActivity.class);
	      it2.putExtra("projectId", projectId);
	      startActivity(it2);
	    }
   }
	
	
	@Override
	public void PromptInfo(String message, String defaultValue) {
		// TODO Auto-generated method stub
		Log.e("PromptInfo", message);//id
		if(TextUtils.isEmpty(message)) return;
		if(!message.contains(",")) return;
		//CommonUtil.showToast(message+"|"+defaultValue, this);
		 String[] tmpArr=message.split(",");
 
	      if( "1".equals(tmpArr[0])){
	    	  if(tmpArr[1].equals("0")) return;
 	  	  	  Intent it = new Intent(this, BaiduMapActivity.class);
 		 	  it.putExtra("latitude", Double.parseDouble(tmpArr[2]));
		 	  it.putExtra("longitude", Double.parseDouble(tmpArr[1]));
		 	  it.putExtra("address", "");
		 	  startActivity(it);
 	      }
	      else if( "2".equals(tmpArr[0]))
	      {
	    	  pId =  Integer.parseInt(tmpArr[1]);
	    	  pName = tmpArr[2];
	    	  DialogBuilder builder2 = new DialogBuilder(Project_info_lience.this);
	   		  builder2.setParentlayout(R.layout.custom_ucenter_dialog);
	          builder2.setContentView(R.layout.u_center_verify_send_email); //ac_dialog_cancel; 
	          final EditText pwdedit=(EditText)builder2.getCurContentView().findViewById(R.id.pwd_editText);
	          if( null != AppSetting.curUser){
	        	  if( null != AppSetting.curUser.uemail && !"".equals(AppSetting.curUser.uemail)){
		        	  pwdedit.setText(AppSetting.curUser.uemail);
		    	  }
	          }
 	          builder2.setCloseOnclick(new OnClickListener(){
	   			    @Override
	  				public void onClick(View arg0) {
	   			    	if(arg0.getId()==R.id.btn_cancel){
	   			    		CheckPwdDialog.dismiss();
	   			    		return;
	   			    	}
	   			    	if(pwdedit.getText()==null||pwdedit.getText().toString()==""){
	   			    		CommonUtil.showToast("����������", Project_info_lience.this);
	   			    		return;
	   			    	}
	   			    	if(!CommonUtil.isEmail(pwdedit.getText().toString())){
  							CommonUtil.showToast("��������ȷ������", Project_info_lience.this);
  							return;
  						}
	   			    	CheckPwdDialog.dismiss();
	  					sendEmail(pwdedit.getText().toString(), pId, pName);
 	  							
  	  				 }
	  		   }); 
	          CheckPwdDialog = builder2.create();
	          CheckPwdDialog.show();
		
	      }
	      else if( "3".equals(tmpArr[0])){
	    	  pId =  Integer.parseInt(tmpArr[1]);
	    	  uname = tmpArr[2];
	    	  uid = Long.parseLong(tmpArr[3]);
	    	  
	    	  if( null != AppSetting.curUser){
	  				 Intent it4 = new Intent(Project_info_lience.this, Project_commentActivity.class);
					 it4.putExtra("projectId", pId);
					 it4.putExtra("targetId", uid);
					 it4.putExtra("targetName", uname);
				     startActivity(it4);
				 }else{
					 Intent it = new Intent(this, User_phone_login.class);
			 		 it.putExtra("forResult", true);
					 this.startActivityForResult(it,104);
		 		 }
	      }
	      else if( "4".equals(tmpArr[0])){
	 			 Intent it = new Intent(Project_info_lience.this, Project_commentlist_Activity.class);
			     it.putExtra("projectId", projectId);
				 startActivity(it);
	      }else if( "5".equals(tmpArr[0])){
	    	  goWritecomment(Project_commentActivity.class,102);
	      }
	    else if( "6".equals(tmpArr[0])){
	    	    if(TextUtils.isEmpty(tmpArr[1]))  { return;}
	    	    
 	     	    Intent it = new Intent(Project_info_lience.this, Project_cityInfoActivity.class);
			    it.putExtra("postCode",Integer.valueOf(tmpArr[1]).intValue());//421182 
				startActivity(it); 
	      } 
	}

	
	public void sendEmail(String email,int pId,String pName){
		 RequestParams param = new RequestParams();
		 param.put("email", email);
		 param.put("projectId", pId);
		 param.put("projectName", pName);
		 
		 ZrbRestClient.post("proEmailApi/insert" , param,
						new AsyncHttpResponseHandler() {

							@Override
							public void onFailure(int arg0, Header[] arg1, byte[] arg2,
									Throwable arg3) {
								CommonUtil.showToast("���糬ʱ,����������", Project_info_lience.this);
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
								// TODO Auto-generated method stub
								String results = new String(arg2);
								Log.e("tag", results);
								try {
									  Gson gson = new Gson();
									  UserDtos tmpDto = gson.fromJson(results,UserDtos.class);
 									  CommonUtil.showToast(tmpDto.res==1 ? "�ύ�ɹ�":tmpDto.msg, Project_info_lience.this);
 	 								 
							        } catch (Exception e) {
 									   CommonUtil.showToast("���������쳣",Project_info_lience.this);//fail:"+e.getMessage()
 								    }
 							}
						});
	}

	@Override
	public void ReceivedTitle(String title) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void	onActivityResult(int requestCode, int resultCode, Intent data){
 	    if(resultCode==RESULT_OK){
		  switch (requestCode) { // resultCodeΪ�ش��ı�ǣ�����B�лش�����RESULT_OK
		    case 100:
  			  showfavoriteState();
			  if(!isFavorite) onClickCollect(projectId);
			  break;
		    case 101:
		       Intent it2 = new Intent(Project_info_lience.this, Project_surveyActivity.class);
		       it2.putExtra("projectId", projectId);
			   startActivity(it2);
			   break;
		    case 102:
			       Intent it3 = new Intent(Project_info_lience.this, Project_commentActivity.class);
			       it3.putExtra("projectId", projectId);
				   startActivity(it3);
				   break;
		    case 103:
			       Intent it4 = new Intent(Project_info_lience.this, Project_commentlist_Activity.class);
			       it4.putExtra("projectId", projectId);
				   startActivity(it4);
				   break;
		    case 104:
			       Intent it5 = new Intent(Project_info_lience.this, Project_commentActivity.class);
			       it5.putExtra("projectId", projectId);
				   it5.putExtra("targetId", uid);
				   it5.putExtra("targetName", uname);
				   startActivity(it5);
				   break;
		    case 105:
		    	startChat();
		    	break;
		 
		   default:
			break;
		  }
 	    }
 	    super.onActivityResult(requestCode, resultCode, data);
   } 
	
	public void onClickCollect(int newsId) {
		// TODO Auto-generated method stub
 		if(AppSetting.curUser==null){
 			 Intent it = new Intent(this, User_phone_login.class);
 			 it.putExtra("forResult", true);
			 this.startActivityForResult(it, 100);
		    return;
		}
 		//mCollectionHelper.onClickCollect(newsId,!isFavorite,false);
   }
	
	@Override
	public void onCollectionEvent() {
		// TODO Auto-generated method stub
		//showToast(!isFavorite ?"�ѹ�ע":"ȡ���ע", Project_info_lience.this);
		isFavorite=!isFavorite;
           btnfavorite.setSelected(isFavorite); 
           btnfavorite.setText(isFavorite?"�ѹ�ע":"�� ע");
           btnfavorite.setEnabled(false);
	         new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                	btnfavorite.setEnabled(true);
                }

        }, 2000);
	}
 
 
/*	l  Current horizontal scroll origin. 
	t  Current vertical scroll origin. 
	oldl  Previous horizontal scroll origin. 
	oldt  Previous vertical scroll origin */
	boolean isshow=false;
	@Override
	public void onSChanged(int l, int t, int oldl, int oldt) {
		// TODO Auto-generated method stub
		if(t>(oldt+30)){//���Ϲ�
			if(isshow){
				isshow=false;
				showtoolbar(false);
			}
 		}
		else if((t+30)<oldt){
			if(!isshow){
				isshow=true;
				showtoolbar(true);
			}
			
		}
	}

	
}
